<?php
/**
 * Event.php
 *
 * @copyright   2023 thingsworld.com.cn - All Rights Reserved
 * @link        http://thingsworld.com.cn/
 * @author      stiffer.chen <chenl@thingsworld.com.cn>
 * @created     2023-02-16 03:18:36
 * @modified    2023-02-16 03:18:36
 *
 */

namespace App\Models;

use App\Models\Customer;
use App\Models\Event\Image;
use App\Models\Event\Person;
use App\Models\Event\Receipt;
use App\Models\Event\StatusHistory;
use App\Models\Product;
use App\Repositories\Customer\EventRepo;
use App\Repositories\OperationLogRepo;
use Carbon\Carbon;

class Event extends BaseModel
{
    public $timestamps = true;
    protected $table = 'event';
    protected $fillable = [
        'event_number',
        'type',
        'customer_id',
        'customer_name',
        'customer_user_id',
        'product_id',
        'contact_name',
        'contact_telephone',
        'buy_channel',
        'buy_date',
        'project_name',
        'product_number',
        'province_id',
        'province_name',
        'city_id',
        'city_name',
        'county_id',
        'county_name',
        'address',
        'plan_at',
        'description',
        'created_type',
        'created_by',
        'status',
        'create_user_id',
    ];

    protected $rules = [

    ];

    protected $appends = [
        'type_text',
        'created_type_text',
        'status_text',
        'logs',
        'correlation',
        'create_time_format',
        'update_time_format',
    ];

    public function getCorrelationAttribute()
    {
        $eventId = $this->id;
        $wo = WorkOrder::byEventId($eventId)->first();
        if (empty($wo)) {
            return false;
        }
        return true;
    }

    public function getCreateTimeFormatAttribute()
    {
        return Carbon::parse($this->create_time)->toDateTimeString();
    }

    public function getUpdateTimeFormatAttribute()
    {
        return Carbon::parse($this->update_time)->toDateTimeString();
    }

    public function getTypeTextAttribute()
    {
        $types = collect(EventRepo::params()['types'])->keyBy('code')->toArray();
        return $types[$this->type]['title'] ?? '';
    }

    public function getCreatedTypeTextAttribute()
    {
        $createdTypes = collect(EventRepo::params()['create_types'])->keyBy('code')->toArray();
        return $createdTypes[$this->created_type]['title'] ?? '';
    }

    public function getStatusTextAttribute()
    {
        $status = $this->status;
        $statuses = collect(EventRepo::params()['status'])->keyBy('code')->toArray();
        return $statuses[$status]['title'] ?? '';
    }

    public function getLogsAttribute()
    {
        $logs = OperationLog::byBusinessId($this->id)->byBusinessType(OperationLogRepo::BUSINESS_TYPE_EVENT)->orderBy('id')->get();
        if (empty($logs)) {
            return [];
        }
        $user = $this->users->where('is_master', 1)->toArray()[0] ?? [];
        $userId = $user['user_id'] ?? 0;
        $mobile = '';
        if ($userId) {
            $modelUser = UserModel::find($userId);
            if (!empty($modelUser)) {
                $mobile = $modelUser->mobile ?? '';
            }
        }
        $result = [];
        foreach ($logs as $log) {
            $temp = json_decode($log['business_body'], true);
            $temp['create_time'] = Carbon::parse($log['create_time'])->toDateTimeString();
            $temp['contact_phone'] = $mobile;
            $result[] = $temp;
        }
        return $result;
    }

    public function scopeByNumber($query, $number)
    {
        return $query->where('event_number', $number);
    }

    public function images()
    {
        return $this->hasMany(Image::class);
    }

    public function users()
    {
        return $this->hasMany(\App\Models\Event\User::class);
    }

    public function customer()
    {
        return $this->belongsTo(Customer::class);
    }

    public function customer_user()
    {
        return $this->belongsTo(Customer\User::class);
    }

    public function product()
    {
        return $this->belongsTo(Product::class);
    }

    public function histories()
    {
        return $this->hasMany(StatusHistory::class);
    }

    public function receipt()
    {
        return $this->hasOne(Receipt::class);
    }

    public function work_order()
    {
        return $this->hasOne(WorkOrder::class);
    }
}